package green.mapstore

import green.mapstore.MapStore

public class HashMapStore implements MapStore {

  // MEMBERS

  protected HashMap<Object, Object> store;
  protected File pathFile;

  // CONSTRUCTION

  public HashMapStore(String path) {
    pathFile = new File(path);
  }

  // MANIPULATION OPS

  public void add(Object key, Object value) {
    store.put(key, value);
  }

  void addAll(Map<Object, Object> values) {
    store.putAll(values);
  }

  void delete(Object key) {
    store.remove(key);
  }

  void clear() {
    store.clear();
  }

  // DIAGNOSTIC OPS

  int size() {
    store.size();
  }

  boolean containsKey(Object key) {
    store.containsKey(key);
  }

  // HASHMAP-SPECIFIC DIAGNOSTIC OPS

  boolean existsOnDisk() {
    pathFile.exists()
  }

  // RETRIEVAL OPS

  Object get(Object key) {
    store.get(key)
  }

  Map<Object, Object> getAll() {
    return (Map<Object, Object>) store.clone()
  }

  // LIFECYCLE OPS

  void init() {
    if (pathFile.exists()) {
      ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream(pathFile));
      store = (HashMap<Object, Object>) inputStream.readObject();
      inputStream.close();
    } else {
      store = new HashMap<Object, Object>();
    }
  }

  void commit() {
    ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream(pathFile));
    outputStream.writeObject(store);
    outputStream.close();
  }

}
